package com.ruoyi.web.controller.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class AliyunOssUtils {

    @Value("${alioss.endpoint}")
    private String endpoint;

    @Value("${alioss.access-key-id}")
    private String accessKeyId;

    @Value("${alioss.access-key-secret}")
    private String accessKeySecret;

    @Value("${alioss.bucket-name}")
    private String bucketName;

    /**
     * 上传文件到 OSS
     */
    public String uploadFile(MultipartFile file) {
        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString().replace("-", "") + "-" + originalFilename;

        // 创建 OSS 客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try (InputStream inputStream = file.getInputStream()) {
            // 上传文件到 OSS
            ossClient.putObject(bucketName, fileName, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭 OSS 客户端
            ossClient.shutdown();
        }
        // 返回文件 URL
        return "https://" + bucketName + "." + endpoint + "/" + fileName;
    }
}
